package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import jodd.util.StringUtil;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    // 线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) {
        // 缓存穿透
//        Shop shop = queryWithPassThrough(id);
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, thisId -> getById(thisId),CACHE_SHOP_TTL,TimeUnit.SECONDS );
        // 互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);
        // 逻辑过期解决缓存击穿
//        Shop shop = queryWithLogicalExpire(id);
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, LOCK_SHOP_KEY, LOGICAL_PASS_TTL, TimeUnit.SECONDS);

        // 返回
        if (shop == null) {
            return Result.fail("商铺信息为空");
        }
        return Result.ok(shop);
    }

    // 解决缓存穿透
    // 见工具类

    // 解决缓存击穿，互斥锁
//    public Shop queryWithMutex(Long id) {
//        // 从 redis 查询商铺缓存
//        String key = CACHE_SHOP_KEY + id;
//        String shopJSON = stringRedisTemplate.opsForValue().get(key);
//        // 存在，返回
//        if (StrUtil.isNotBlank(shopJSON)) {  // isNotBlank 只有有实在的内容才判 true
//            Shop shop = JSONUtil.toBean(shopJSON, Shop.class);
//            return shop;
//        }
//        // 判断命中的是否是空值
//        if (shopJSON != null) {
//            // 返回一个错误信息
//            return null;
//        }
//
//        // 实现缓存重建
//        String lock_key = LOCK_SHOP_KEY + id;
//        Shop shop = null;
//        try {
//            // 1. 获取互斥锁
//            boolean lock_flag = tryLock(lock_key);
//            // 2. 判断是否获取成功
//            if (!lock_flag) {
//                // 3. 失败，休眠返回重试
//                Thread.sleep(50);
//                return queryWithMutex(id);  // 递归重新执行
//            }
//            // 4. 成功，根据id查询数据库
//            shop = getById(id);
//            Thread.sleep(200);  // 模拟重建的验延时
//            // 5. 数据库不存在，报错
//            if (shop == null) {
//                // 将空值写入 redis
//                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
//                return null;
//            }
//            // 6. 数据库存在，写入 redis，再返回
//            String shopToJSON = JSONUtil.toJsonStr(shop);
//            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, shopToJSON, CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        } finally {
//            // 7. 释放互斥锁
//            unLock(lock_key);
//        }
//        // 返回
//        return shop;
//    }

    // 逻辑过期时间解决缓存击穿
    // 见工具类

    // 逻辑过期时间方式，先将需要存的数据存入 redis
    // 见工具类

    // 修改商铺
    @Override
    @Transactional  // 事务
    public Result update(Shop shop) {
        if (shop.getId() == null) {
            return Result.fail("店铺id不能为空");
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return null;
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 1. 判断是否根据地理坐标查询
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            return null;
        }
        // 2. 计算分页参数
        int begin = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;
        // 3. 查询 redis，按照距离排序，分页。结果 ： shopId、distance
        // GERSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        GeoResults<RedisGeoCommands.GeoLocation<String>> searchResult =
                stringRedisTemplate.opsForGeo().radius(
                        SHOP_GEO_KEY + typeId,
                        new Circle(new Point(x, y), new Distance(5000)),
                        RedisGeoCommands.GeoRadiusCommandArgs
                                .newGeoRadiusArgs()
                                .includeDistance()
                                .limit(end)
                );
//                stringRedisTemplate.opsForGeo().search(
//                        SHOP_GEO_KEY + typeId,
//                        GeoReference.fromCoordinate(x, y),
//                        new Distance(5000), // m 将来搜索的单位也是 m
//                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs()
//                                .includeDistance()
//                                .limit(end) // 始终从 0 开始
//                );
        // 4.1 解析 id
        if (searchResult == null) return Result.ok(Collections.emptyList());
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = searchResult.getContent();
        // 4.1.1 没有从开始位置往后的数据了，也返回空
        if (list.size() < begin) return Result.ok(Collections.emptyList());
        // 4.2 截取从 begin 到 end 的部分
        // list().subList()
        List<Long> ids = new ArrayList<>(list.size());
        Map<String, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(begin).forEach(r -> {
            // ID
            String shopId = r.getContent().getName();
            ids.add(Long.valueOf(shopId));
            // 距离
            Distance distance = r.getDistance();
            distanceMap.put(shopId, distance);
        });
        if(ids.isEmpty()) return Result.ok(Collections.emptyList());
        // 5. 根据 id 查询 shop
        String idsStr = StrUtil.join(",", ids);
        List<Shop> shops =
                query()
                        .in("id", ids)
                        .last("ORDER BY FIELD(id," + idsStr + ")")
                        .list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        // 返回
        return Result.ok(shops);
    }


}
